<template>
  <div class="menu">
    <!--筛选搜索 -->
    <el-form
      label-width="80px"
      :inline="true"
      size="small"
      class="search"
      v-show="hideShow"
    >
      <el-form-item label="活动名称">
        <el-input placeholder="请输入菜单名称" v-model="menuName"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select placeholder="菜单状态" v-model="status">
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="search()"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="reset()"
          >重置</el-button
        ></el-form-item
      >
    </el-form>
    <!-- 新增数据 \ 展开收起-->
    <div class="header-btn">
      <div class="left">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          plain
          @click="dialogFormVisible = true"
          >新增</el-button
        >
        <el-button
          type="info"
          icon="el-icon-sort"
          size="mini"
          plain
          @click="openTable()"
          >展开/折叠</el-button
        >
      </div>
      <div class="right">
        <el-tooltip
          class="item"
          effect="dark"
          :content="hideSearch"
          placement="top"
        >
          <el-button
            icon="el-icon-search"
            circle
            size="mini"
            @click="clickFn"
          ></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button
            icon="el-icon-refresh"
            circle
            size="mini"
            type="primary"
            plain
            @click="search()"
          ></el-button>
        </el-tooltip>
      </div>
    </div>
    <!-- 表格数据 -->
    <el-table
      :data="menu"
      style="width: 100%; margin-bottom: 20px"
      row-key="menuId"
      :tree-props="{ children: 'children' }"
      class="table"
      :default-expand-all="showTable"
      v-if="refTable"
    >
      <el-table-column
        prop="menuName"
        label="菜单名称"
        width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column label="图标" prop="icon" align="center">
        <template #default="{ row }">
          <img :src="icons[row.icon]" alt="" width="14" height="14" />
          <!-- <svg-icon :icon-file-name="row.icon"/> -->
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="60">
      </el-table-column>
      <el-table-column label="权限标识" prop="perms"> </el-table-column>
      <el-table-column label="组件路径" prop="component"> </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag v-if="row.status === '0'">正常</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        width="191"
      >
      </el-table-column>

      <el-table-column label="操作" align="center" width="191">
        <template #default="{ row }">
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            @click="showEdit(row.menuId)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-plus"
            @click="dialogFormVisible = true"
            >新增</el-button
          >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-delete"
            @click="open(row.menuName, row.menuId)"
          >
            删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加/修改菜单 -->
    <el-dialog
      :title="menuTitle"
      :visible.sync="dialogFormVisible"
      :inline="true"
    >
      <el-form :model="form" inline style="font-weight: bold">
        <el-form-item label="上级菜单" :label-width="formLabelWidth">
          <el-select v-model="form.parentName" placeholder="请选择上级菜单">
            <el-option
              :value="form.parentId"
              :label="form.parentName"
              style="height: auto"
            >
              <el-tree
                :data="treeMenu"
                :props="defaultProps"
                @node-click="changeMenuTop"
              ></el-tree>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单类型" :label-width="formLabelWidth">
          <el-radio-group v-model="form.menuType" class="widthLength">
            <el-radio label="M">目录</el-radio>
            <el-radio label="C">菜单</el-radio>
            <el-radio label="F">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="菜单图标"
          :label-width="formLabelWidth"
          v-show="form.menuType !== 'F'"
        >
          <el-select v-model="form.icon" placeholder="点击选择图标">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-option :value="form.icon">
              <el-input placeholder="请输入图标名称" v-model="form.icon">
                <i slot="suffix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="菜单名称"
          :label-width="formLabelWidth"
          :rules="{
            required: true,
            message: '菜单名称不能为空',
            trigger: 'blur',
          }"
          prop="menuName"
        >
          <el-input
            v-model="form.menuName"
            placeholder="请输入菜单名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="显示排序"
          :label-width="formLabelWidth"
          :rules="{
            required: true,
            message: '菜单顺序不能为空',
            trigger: 'blur',
          }"
          prop="orderNum"
        >
          <el-input-number
            v-model="form.orderNum"
            controls-position="right"
            :min="1"
            :max="10"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="是否外链"
          :label-width="formLabelWidth"
          v-show="form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    是否外链
                  </span>
          <el-radio-group v-model="form.isFrame" class="contentWidth">
            <el-radio label="0">是</el-radio>
            <el-radio label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="路由地址"
          :label-width="formLabelWidth"
          :rules="{
            required: true,
            message: '路由地址不能为空',
            trigger: 'blur',
          }"
          prop="path"
          v-show="form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    路由地址
                  </span>
          <el-input v-model="form.path" placeholder="请输入路由地址"></el-input>
        </el-form-item>
        <el-form-item
          label="组件路径"
          :label-width="formLabelWidth"
          v-show="form.menuType == 'C' && form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    组件路径
                  </span>
          <el-input
            v-model="form.component"
            placeholder="请输入组件路径"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="权限字符"
          :label-width="formLabelWidth"
          v-show="form.menuType == 'C' && form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    权限字符
                  </span>
          <el-input
            v-model="form.perms"
            placeholder="请输入权限标识"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="路由参数"
          :label-width="formLabelWidth"
          v-show="form.menuType == 'C' && form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    路由参数
                  </span>
          <el-input
            v-model="form.query"
            placeholder="请输入路由参数"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="是否缓存"
          :label-width="formLabelWidth"
          v-show="form.menuType == 'C' && form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    是否缓存
                  </span>
          <el-radio-group v-model="form.isCache" class="contentWidth">
            <el-radio label="0">缓存</el-radio>
            <el-radio label="1">不缓存</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="显示状态"
          :label-width="formLabelWidth"
          v-show="form.menuType !== 'F'"
        >
        <span slot="label">
                    <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    显示状态
                  </span>
          <el-radio-group v-model="form.visible" class="contentWidth">
            <el-radio label="0">显示</el-radio>
            <el-radio label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="菜单状态"
          :label-width="formLabelWidth"
          prop="status"
        >
        <span slot="label">
                    <el-tooltip content='选择停用则路由将不会出现在侧边栏，也不能被访问' placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                    菜单状态
                  </span>
          <el-radio-group v-model="form.status" class="contentWidth">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sub(form.menuId)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  MenuApi,
  MenuTreeApi,
  MenuDellApi,
  MenuAddApi,
  MenuEditApi,
  MenuDetailApi,
} from "@/API/hc-api/index";
import { icons } from "@/assets/icons/index";
import time from "@/utils/time";
export default {
  data() {
    return {
      icons,
      //  树形解构
      treeMenu: [],
      num: 1,
      menuName: "",
      status: "",
      showTable: false, // 菜单列表
      menu: [],
      dialogFormVisible: false,
      form: {
        parentId: "",
        parentName: "",
        menuName: "",
        menuType: "M",
        orderNum: 0,
        icon: "",
        isFrame: "1",
        visible: "0",
        status: "0",
        path: "",
        children: [],
        createTime: time.getDetailedDate(),
        perms: "",
        isCache: "0",
        component: "",
        query: "",
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      label: "",
      formLabelWidth: "100px",
      refTable: true,
      hideShow: true,
      hideSearch: "隐藏搜索",
      menuTitle: "添加菜单",
    };
  },
  methods: {
    // 请求菜单列表
    async getMenuData(menuName, status) {
      let res = await MenuApi(menuName, status);
      if (menuName || status) {
        // 默认所有数据都是第一级
        res.data.forEach((item) => (item.isone = true));
        for (let i = 0; i < res.data.length - 1; i++) {
          for (let j = i + 1; j < res.data.length; j++) {
            // 如果上一个菜单是下一个才大的父级
            if (res.data[j].parentId === res.data[i].menuId) {
              res.data[i].children.push(res.data[j]);
              res.data[j].isone = false;
            }
            // 如果上一个菜单是下一个菜单人子集
          }
        }

        for (let i = 0; i < res.data.length; i++) {
          if (!res.data[i].isone) {
            res.data.splice(i, 1);
            i--;
          }
        }
        // console.log(res.data);
        this.menu = res.data;
      } else {
        this.menu = res.data.filter((item) => item.parentId === 0);
        this.menu.forEach((item) => {
          let twoObj = res.data.filter((a) => a.parentId === item.menuId);
          item.children = twoObj;
          item.children?.forEach((thr) => {
            let thrObj = res.data.filter((a) => a.parentId === thr.menuId);
            thr.children = thrObj;
          });
        });
      }
    },

    // 删除数据请求
    async delMenu(id) {
      let res = await MenuDellApi(id);
      console.log(res);
    },
    // 树状结构
    async getTreeMenu() {
      let res = await MenuTreeApi();

      this.treeMenu = [{ id: 0, label: "主类目", children: [] }];
      this.treeMenu[0].children = res.data;
    },
    // 删除方法
    open(detail, id) {
      this.$confirm(`是否确认删除名称为"${detail}"的数据项?`, "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delMenu(id);
          this.getMenuData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 菜单修改请求

    async editMenu(params) {
      await MenuEditApi(params);
    },

    // 增加数据里的上级菜单
    changeMenuTop(data) {
      this.form.parentName = data.label;
      this.form.parentId = data.id;
    },

    // 确认添加数据
    async MenuAdd(params) {
      await MenuAddApi(params);
      this.dialogFormVisible = false;
    },
    // 打开编辑按钮
    async showEdit(id) {
      let res = await MenuDetailApi(id);
      // Object.assign(this.form, res.data);
      if (!res.data.parentName) {
        res.data.parentName = "主类目";
        this.form = res.data;
      }
      this.menuTitle = "修改菜单";
      this.dialogFormVisible = true;
    },
    // 确定添加或修改
    sub(menuId) {
      if (menuId) {
        this.editMenu(this.form);
      } else {
        this.MenuAdd(this.form);
      }
      this.getMenuData();
      this.dialogFormVisible = false;
    },
    // 展开收起
    openTable() {
      this.showTable = !this.showTable;
      // console.log(this.showTable);
      this.refTable = false;

      this.$nextTick(() => {
        this.refTable = true;
      });
    },
    // 重置
    reset() {
      this.getMenuData();
      this.menuName = "";
      this.status = "";
    },
    // 搜索
    async search() {
      let params = {
        menuName: this.menuName,
        status: this.status,
      };
      this.getMenuData(params);
    },
    clickFn() {
      this.hideShow = !this.hideShow;
      if (this.hideShow) {
        this.hideSearch = "隐藏搜索";
      } else {
        this.hideSearch = "显示搜索";
      }
    },
  },
  watch: {
    dialogFormVisible(to, from) {
      if (!this.dialogFormVisible) {
        this.form = {
          parentId: "",
          parentName: "",
          menuName: "",
          menuType: "M",
          orderNum: 0,
          icon: "",
          isFrame: "1",
          visible: "0",
          status: "0",
          path: "",
          children: [],
          createTime: "",
          perms: "",
        };
        this.menuTitle = "添加菜单";
      }
    },
  },

  created() {
    this.getMenuData();
    this.getTreeMenu();
  },
};
</script>
<style lang="less" scoped>
.header-btn {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}
/deep/ .el-table .el-table__header-wrapper th {
  background-color: #f8f8f9;
  color: #515a6e;
  height: 40px;
  font-size: 13px;
  font-weight: bold;
}
/deep/ .el-table__header-wrapper,
.el-table__body-wrapper {
  margin: 20px auto;
}
/deep/ .el-select .el-input__inner,
.widthLength {
  width: 500px;
}
/deep/ .el-form-item__content .contentWidth {
  width: 185px;
}
.menu {
  width: 100%;
}
</style>
